<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use app\admin\model\XPersonalremind;
/**
 * 拜访记录
 *
 */
class Visit extends Backend
{
    /**
     * Visit模型对象
     * @var \app\admin\model\Visit
     */
    protected $model = null;
    
    protected $quickSearchField = ['VISITID'];

    protected $defaultSortField = 'VISITID,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Visit;
    }
    /**
     * 添加
     */
    public function add()
    {


        if ($this->request->isPost()) {
            $adminInfo          = $this->auth->getInfo();
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                if(isset($data['XPER']) && $data['XPER']==1){
                    $PERSONALREMIND=[
                      'VISITID'=>$this->model->VISITID,
                        'RQ'=>$data['XPERTIME'],
                        'REMIND'=>$data['CORPNAME'].','.$data['NEXTDETAIL'].','.$data['SALER'],
                        'ACTIVED'=>0,
                        'OP'=>$data['OP'],
                        'OPTIME'=>$data['OPTIME']
                    ];
                    (new XPersonalremind())->save($PERSONALREMIND);
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }
}